/*
 * Copyright (c) 2018-2023 北京华恒盛世科技有限公司
 * QUICKPOOL is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
*/

#include "subcmd.h"

static void readmsg_usage(const char *);

/**
 * @brief       qp job read handler, to read message of a job in the cluster.
 *
 * @param[in]   argc          #1: number of input argument
 * @param[in]   argv          #2: string array of the input argument
 *
 * @retval      0             #1: succeed
 * @retval      1             #2: input option is wrong or kind of input argument not specified
 * @retval      2             #3: argument has syntax error
 * @retval      3             #4: failed to read message of the job
 */
int
cmd_read_message(int argc, char **argv)
{
    while (TRUE) {
        int option_index = 0;
        static struct option long_options[] = {
            {"help", no_argument, 0, 'h'},
            {NULL, 0, 0, 0}
        };

        int opt;
        opt = getopt_long(argc, argv, "h", long_options, &option_index);
        if (-1 == opt) {
            break;
        }

        switch (opt) {
        case 'h':
            readmsg_usage(argv[0]);
            exit(0);
        case '?':
        default:
            readmsg_usage(argv[0]);
            exit(1);
        }
    }

    if (argc <= optind) {
        fprintf(stderr, "Must specify a job ID.\n");
        readmsg_usage(argv[0]);
        exit(1);
    }

    // get the job ID for reading its message.
    JOBID_T jobId;
    if (get_one_jobid(argv[argc - 1], &jobId)) {
        exit(2);
    }

    struct request messageRequest;
    messageRequest.number = 1;
    messageRequest.keyvalues = (struct keyvalue *)calloc(messageRequest.number,
                                                         sizeof(struct keyvalue));
    if (NULL == messageRequest.keyvalues) {
        fprintf(stderr, "calloc(%ld) failed due to %m.\n",
                messageRequest.number*sizeof(struct keyvalue));
        exit(4);
    }

    messageRequest.keyvalues[0].key = REQUEST_KEY_JOBIDS;
    messageRequest.keyvalues[0].value = (char *)calloc(32, sizeof(char));
    if (NULL == messageRequest.keyvalues[0].value) {
        fprintf(stderr, "calloc(%d) failed due to %m.\n", 32);
        exit(4);
    }
    snprintf(messageRequest.keyvalues[0].value, 32, "%lld", jobId);

    struct QuickPoolJobMsgReply *msgReply;
    msgReply = client_read_jobmessage(&messageRequest, NULL);
    if (quickpool_errno != 0 || NULL == msgReply) {

        if (NULL == msgReply) {
            fprintf(stderr, "Fail to read job message due to above error.\n");
        } else {
            // JS replied error message.
            fprintf(stderr, "%s\n", msgReply->error_message);

            gf_xdr_free(libxdr_jobmsg_reply, msgReply);
            FREEUP(msgReply);
        }

        gf_xdr_free(gf_xdr_request, &messageRequest);

        exit(3);
    }

    gf_xdr_free(gf_xdr_request, &messageRequest);

    if (0 == msgReply->num_message) {
        char strJobId[32];
        fprintf(stderr, "%s: Job <%s> has no posted message.\n",
                __func__, jobid_2string(jobId, strJobId));
        exit(0);
    }

    json *jsonMessage = json_CreateObject();
    json_AddNumberToObject(jsonMessage, "JOBID", ARRAY_JOBID(jobId));
    if (0 < ARRAY_INDEX(jobId)) {
        json_AddNumberToObject(jsonMessage, "JOB_INDEX", ARRAY_INDEX(jobId));
    }

    unsigned int i;
    for (i=0; i<msgReply->num_message; i++) {

        json *jsonMsg = json_CreateObject();
        json_AddNumberToObject(jsonMsg, "MESSAGE_ID", i+1);

        char timebuf[TIMESTRINGLEN];
        ctime_2string(CTIME_FORMAT_a_b_d_T_Y, &(msgReply->messages[i].post_time), timebuf);
        json_AddStringToObject(jsonMsg, "POST_TIME", timebuf);
        json_AddStringToObject(jsonMsg, "CONTENT", msgReply->messages[i].message);

        json_AddItemToObject(jsonMessage, "MESSAGE", jsonMsg);
    }

    char *strJson;
    strJson = json_Print(jsonMessage);
    if (NULL != strJson) {
        fprintf(stdout, "%s\n", strJson);
        FREEUP(strJson);
    } else {

        perror("malloc");
        json_Delete(jsonMessage);
        gf_xdr_free(libxdr_jobmsg_reply, msgReply);
        FREEUP(msgReply);

        exit(4);
    }
    json_Delete(jsonMessage);

    gf_xdr_free(libxdr_jobmsg_reply, msgReply);
    FREEUP(msgReply);

    exit(0);
} // end function cmd_read_message

static void
readmsg_usage(const char *cmd)
{
    fprintf(stderr, "qp job %s usage: [-h, --help] jobId\n", cmd);

    return;
}
